package mysql

import (
	"bluebell/models"
	"bluebell/pkg/md5encoder"
	"database/sql"
	"errors"
)

// CheckUserExist 检测用户是否存在(根据用户名)
func CheckUserExist(phone string) (err error) {
	slqStr := `select count(id) from user where phone = ?`
	var count int
	if err := db.Get(&count, slqStr, phone); err != nil {
		return err
	}
	if count > 0 {
		return errors.New("用户已存在")
	}
	return
}

// InsertUser 新增一条用户数据
func InsertUser(user *models.User) (err error) {
	sqlStr := `insert into user(user_id,phone,password) values(?,?,?)`
	pwd := md5encoder.GetMD5Encode(user.Password) // 密码加密
	_, err = db.Exec(sqlStr, user.UserID, user.Phone, pwd)
	return
}

// Login 登录查询
func Login(params *models.ParamLogin) (user *models.User, err error) {
	user = &models.User{}
	sqlStr := `select id,user_id,password from user where phone=?`
	pwd := md5encoder.GetMD5Encode(params.Password)                     // 密码加密
	if err = db.Get(user, sqlStr, params.Phone); err == sql.ErrNoRows { // sql.ErrNoRows未查到数据返回的错误
		err = errors.New("用户不存在")
	}
	if pwd != user.Password {
		err = errors.New("密码错误")
	}
	return
}

func GenUserById(uid int64) (user *models.User, err error) {
	sqlStr := `select * from user where user_id=?`
	user = &models.User{}
	if err = db.Get(user, sqlStr, uid); err == sql.ErrNoRows { // sql.ErrNoRows未查到数据返回的错误
		return nil, errors.New("用户不存在")
	}
	return
}
